package com.ygsj;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.ygsj.Utils.OkhttpUtils;
import com.ygsj.Utils.ParJson;
import com.ygsj.Utils.UHFUtils;
import com.ygsj.ui.loader.Loader;

import java.io.IOException;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Response;

import static com.uhf.uhf.Common.Comm.isrun;

public class LoginActivity extends AppCompatActivity {
    private static final String TAG = "LoginActivity";
    private UHFUtils uhfUtils;
    private Button btn_login;
    private ConstraintLayout con_loginActivity;
    String zt, pwd;//flag登录成功或者失败的标志;
    String imei;//mac地址;
    String name_person;//userName是系统管理员的用户名,name是使用者的用户名
    EditText et_zt, et_userName, et_pwd;
    private boolean networkAvailable;
    Handler loginHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0://登录成功
                    Map map = (Map) msg.obj;
                    String userName_ = (String) map.get("gsdbztxx_owner");
                    String pwd_ = (String) map.get("gsdbztxx_pass");
                    String dbname = (String) map.get("gsdbztxx_base");
                    String mmname = (String) map.get("mmname");//站点名称
                    String uuname = (String) map.get("uuname");//用户名
                    String goOutPower = (String) map.get("goOutPower");
                    String confirmPower = (String) map.get("confirmPower");
                    Loader.stopLoading();

                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    if (userName_ != null) intent.putExtra("userName", userName_);
                    if (pwd != null) intent.putExtra("pwd", pwd_);
                    if (dbname != null) intent.putExtra("dbname", dbname);
                    if (!TextUtils.isEmpty(name_person)) intent.putExtra("name", name_person);
                    intent.putExtra("mmname", mmname);
                    intent.putExtra("uuname", uuname);
                    intent.putExtra("imei", imei);
                    intent.putExtra("goOutPower",goOutPower);
                    intent.putExtra("confirmPower",confirmPower);
                    startActivity(intent);
                    finish();
                case 1:
                    break;
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        uhfUtils = UHFUtils.getInstance();
        imei = uhfUtils.getIMEI(this);//获取imei;
        initView();
        networkAvailable = uhfUtils.isNetworkAvailable(this);
        if (!networkAvailable) {
           // btn_login.setEnabled(false);
            Toast.makeText(this, "网络无连接,请检查相关配置", Toast.LENGTH_SHORT).show();
        }

    }

    private void initView() {
        con_loginActivity = findViewById(R.id.con_login);
        btn_login = findViewById(R.id.btn_login);
        et_zt = findViewById(R.id.edt_zt);
        et_userName = findViewById(R.id.et_station);
        et_pwd = findViewById(R.id.et_pwd);
        et_zt.setText("");

    }

    /*登录*/
    private void signIn() {
        name_person = et_userName.getText().toString();
        pwd = et_pwd.getText().toString();
        zt = et_zt.getText().toString();
        FormBody.Builder builder = new FormBody.Builder();
        if (TextUtils.isEmpty(zt)) {
            Toast.makeText(this, "请选择套账", Toast.LENGTH_SHORT).show();
        } else {
            builder.add("ztcode", zt);
        }

        if (TextUtils.isEmpty(name_person)) {
            Toast.makeText(this, "请输入用户名", Toast.LENGTH_SHORT).show();
        } else {
            builder.add("code", name_person);
        }

        if (TextUtils.isEmpty(pwd)) {
            Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
        } else {
            builder.add("password", pwd);
        }
        if (!TextUtils.isEmpty(imei)) builder.add("MacCode", imei);
        // Log.e(TAG, "signIn: "+imei );
        Loader.showLoading(LoginActivity.this);

        OkhttpUtils.post_GetJson(GloableUrl.login, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(LoginActivity.this, "请检查网络或联系管理员", Toast.LENGTH_SHORT).show();
                        Loader.stopLoading();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String json = response.body().string();
                Log.e("onSuccess", "onResponse: " + json);
                String flag = ParJson.getLoginData(json);
                String msg = ParJson.getLoginMsg(json);
                Map map = ParJson.getLoginMap(json);
                if (flag != null) {
                    if (flag.equals("0")) {
                        Message message = Message.obtain();
                        message.what = 0;
                        message.obj = map;
                        loginHandler.sendMessage(message);
                    } else if (flag.equals("1")) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(LoginActivity.this, "用户名或密码不正确", Toast.LENGTH_SHORT).show();
                                Loader.stopLoading();

                            }
                        });
                    } else if (flag.equals("2")) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(LoginActivity.this, "无手持机权限", Toast.LENGTH_SHORT).show();
                                Loader.stopLoading();

                            }
                        });
                    } else if (flag.equals("3")) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(LoginActivity.this, "数据库连接失败", Toast.LENGTH_SHORT).show();
                                Loader.stopLoading();
                            }
                        });
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(LoginActivity.this, "用户名不合法", Toast.LENGTH_SHORT).show();
                                Loader.stopLoading();
                            }
                        });

                    }
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(LoginActivity.this, "服务器未返回数据请找管理员", Toast.LENGTH_SHORT).show();
                            Loader.stopLoading();
                        }
                    });
                }

            }
        }, builder);
    }

    public void click_login(View view) {//点击登录
        // startActivity(new Intent(LoginActivity.this,ConfirmActivity.class));
        if (networkAvailable){
            signIn();//进行登录判断;
        }else {
            Toast.makeText(this, "网络无法连接,请检查相关配置", Toast.LENGTH_SHORT).show();
        }

    }

    /*模拟点击登录*/
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (con_loginActivity.isShown()) {
            if (event.getScanCode() == 261 && !isrun)
                btn_login.performClick();
        }
        return super.onKeyUp(keyCode, event);

    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent e) {
        try {
            return super.dispatchKeyEvent(e);
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

    /*通过点击textview的对话框选择套账*/
    public void choice_zt(View view) {
        final String[] array_zt = getResources().getStringArray(R.array.taozhang);
        AlertDialog alertDialog = new AlertDialog.Builder(this, R.style.appalertdialog)
                .setTitle("请选择账套")
                .setIcon(R.mipmap.icon)
                .setItems(array_zt, new DialogInterface.OnClickListener() {//添加列表
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        String ztId = null;
                        if (i < 10) ztId = "00" + (i + 1);
                        else if (i < 100) ztId = "0" + (i + 1);
                        else ztId = (i + 1) + "";
                        et_zt.setText(ztId);
                    }
                })
                .create();
        alertDialog.show();
    }
}